package com.ekang.admin.web;

import com.ekang.admin.common.BaseResult;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by admin on 2017/10/25.
 */
@Controller
public class QrcodeController {

    private static Log log = LogFactory.getLog(QrcodeController.class);


    /**
     * qrcode上传
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {

        BaseResult baseResult = new BaseResult();
        baseResult.setCode("1");

        //Base64编码过的图片数据信息，对字节数组字符串进行Base64解码
        String fileData = request.getParameter("formFile");
        //进行文件上传操作，上传到服务器中存放（这里是上传到服务器项目文件夹中存到）
        String imgPath = uploadFile(fileData);
        //qrcode解码
        String code = qrcodeDecode("./" + imgPath);
        baseResult.setData(code);

        return new ResponseEntity(baseResult, null, HttpStatus.OK);
    }


    /**
     * 文件上传
     *
     * @param fileData
     * @return
     */
    public String uploadFile(String fileData) throws Exception {

        FileOutputStream out = null;
        String filetype = "png";
        String fileName = UUID.randomUUID().toString() + "." + filetype;
        try {

            String base64Code = fileData.substring(fileData.indexOf(",") + 1);
            Base64 base64 = new Base64();
            byte[] bytes = base64.decodeBase64(new String(base64Code).getBytes());
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);

            in = new ByteArrayInputStream(bytes);


            byte[] buffer = new byte[1024];
            String temp_path = ".";
            out = new FileOutputStream(temp_path + File.separator + fileName);
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                if (bytesum > 2 * 1024 * 1024) {
                }
                bytesum += byteread;
                out.write(buffer, 0, byteread); // 文件写操作
            }
            out.flush();

        } catch (Exception e) {
            log.error("e:{}", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return fileName;
    }


    private String qrcodeDecode(String pathFileName) {

        try {
            MultiFormatReader multiFormatReader = new MultiFormatReader();

            File file = new File(pathFileName);

            BufferedImage image = ImageIO.read(file);

            LuminanceSource source = new BufferedImageLuminanceSource(image);

            Binarizer binarizer = new HybridBinarizer(source);

            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

            Map hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            Result result = multiFormatReader.decode(binaryBitmap, hints);

            log.info("result: " + result.toString());
            log.info("resultFormat: " + result.getBarcodeFormat());
            log.info("resultText: " + result.getText());

            return result.getText();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

}
